package com.yybray.spliterator;

import java.util.stream.Stream;

/**
 * Created by Bray on 2017/6/14.
 */
public class StreamWordCounter {

    private int counter;
    private boolean lastSpace;

    public StreamWordCounter(int counter, boolean lastSpace) {
        this.counter = counter;
        this.lastSpace = lastSpace;
    }

    public StreamWordCounter accumulate(Character c) {
        if (Character.isWhitespace(c)) {
            return lastSpace ? this : new StreamWordCounter(counter, true);
        } else {
            return lastSpace ? new StreamWordCounter(counter + 1, false) : this;
        }
    }

    public StreamWordCounter combine(StreamWordCounter wordCounter) {
        return new StreamWordCounter(counter + wordCounter.counter, wordCounter.lastSpace);
    }

    public static int countWords(Stream<Character> stream) {
        StreamWordCounter wordCounter = stream.reduce(new StreamWordCounter(0, true),
                StreamWordCounter::accumulate,
                StreamWordCounter::combine);
        return wordCounter.getCounter();
    }

    public int getCounter() {
        return counter;
    }

}
